﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyFrog : Enemy
{
    public Transform leftPos, rightPos;
    //public Collider2D enemyCollider;
    public LayerMask ground;
    private Rigidbody2D rb;
    private bool isFaceLeft = true;
    private float speed = 100,jumpForce = 5;
    private float leftLimit, rightLimit;

    protected override void Start()
    {
        base.Start();
        rb = GetComponent<Rigidbody2D>();
        //enemyCollider = rb.GetComponent<Collider2D>();

        leftLimit = gameObject.transform.position.x - 10;
        rightLimit = gameObject.transform.position.x + 10;
        InvokeRepeating("RangeMove", 0, 2f);

    }

    void Update()
    {
        //FrogMove();
        AnimSwitch();

    }
    void FrogMove()
    {
        if (enemyCollider.IsTouchingLayers(ground))
        {
            //Debug.Log(isFaceLeft);
            if (isFaceLeft)
            {
                rb.transform.localScale = new Vector2(1, 1);
                anim.SetBool("jumping", true);
                rb.velocity = new Vector2(-speed * Time.deltaTime, jumpForce);

                if(gameObject.transform.position.x < leftLimit)
                {
                    isFaceLeft = false;
                }
            }
            else
            {
                anim.SetBool("jumping", true);
                rb.velocity = new Vector2(speed * Time.deltaTime, jumpForce);
                rb.transform.localScale = new Vector2(-1, 1);

                if (gameObject.transform.position.x > rightLimit)
                {
                    isFaceLeft = true;
                }
            }
        }


    }
    void RangeMove()
    {
        if (Random.Range(0, 100) > 30)
        {
            if (rb.position.x > leftLimit && rb.position.x < rightLimit)
            {
                //(Random.Range(0, 100) > 50) ? (isFaceLeft = true) : (isFaceLeft = false);
                if (Random.Range(0, 100) > 50)
                {
                    isFaceLeft = true;
                }
                else
                {
                    isFaceLeft = false;
                }
            }
            FrogMove();
        }  
    }
    void AnimSwitch()
    {
        if (rb.velocity.y < 0.1f && anim.GetBool("jumping"))
        {
            //Debug.Log("AnimSwitch");
            anim.SetBool("jumping", false);
            anim.SetBool("falling",true);
        }

        if (enemyCollider.IsTouchingLayers(ground))
        {
            //Debug.Log("anim.SetBool(falling false);");
            anim.SetBool("falling", false);
        }
    }


}
